//
//  LMNetworkTools+Extension.swift
//  WeiBo
//
//  Created by Li MAc on 2018/11/18.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import Foundation


extension LMNetworkTools {
    
    //加载微博数据字典数组
    // completion:(_ list 回调字典数组  isSuccess:Bool 回调是否成功
    func statusList(since_id:Int64 = 0 ,max_id:Int64 = 0, completion:@escaping (_ list:[[String:AnyObject]]?,_ isSuccess:Bool)->()){
        let urlstring = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parma = [
            "since_id":"\(since_id)",
            "max_id":"\(max_id>0 ? max_id-1 :0)"
                    ]
        
        tokenQuset(URLString: urlstring, parameters: parma as [String : AnyObject]) { (josn, isSuccess) in
            //从josn中提取需要的数据（）statuses是一个字典数组 一下将其转换
            let res = josn?["statuses"] as? [[String : AnyObject]]
            
//            print(josn)
            
            completion(res ,isSuccess)
        }
    }
}

// MARK：-用户信息
extension LMNetworkTools{
    
    func lodUserInfo(completion:@escaping (_ dict:[String:AnyObject])->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        guard let uid = userSG.uid else{
            return
        }
        let params = ["uid":uid]
        
        //发起网络请求
        tokenQuset(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSueerss) in
            completion((json as? [String:AnyObject] ?? [:]))
        }
    }
    
}




extension LMNetworkTools {
    func loadAT(code:String ,completion:@escaping (_ isSuccess:Bool)->()){
    
    let urlstr = "https://api.weibo.com/oauth2/access_token"
    
        let params = ["client_id":LMAppKey,
                      "client_secret":LMAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":LMURI]
        
        //发起网络请求
        request(method: .POST, URLString: urlstr, parameters: params as [String : AnyObject]) { (josn, isSuccess) in
            
            self.userSG.yy_modelSet(with: (josn as? [String:AnyObject]) ?? [:])
            print("self.userSG---------\(self.userSG)")
            
            //保存模型
            self.userSG.saveAccout()
            
            //加载用户信息
            self.lodUserInfo(completion: { (dict) in
                print(dict)
                //使用用户信息字典将数据用户账户信息（昵称和d头像地址）
                self.userSG.yy_modelSet(with: dict)
                completion(isSuccess)
            })
            
            
        }
    }
}
